<?php

namespace App\Http\Controllers\Attr;

use App\Models\Attr;
use App\Models\CategoryAttr;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AttrController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // 获取所有属性
        $attrs=Attr::paginate(10);
        // 加载属性列表
        return view('attr.index',compact('attrs'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // 获取属性表中所有顶级属性
        $attrs=Attr::where('pid',0)->get();
        // 加载属性表页面
        return view('attr.create',compact('attrs'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // 将数据存入属性表
        Attr::create($request->all());
        // 调转到首页
        return redirect()->route('attr.attr.index')->with('success','添加成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Attr  $attr
     * @return \Illuminate\Http\Response
     */
    public function show(Attr $attr)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Attr  $attr
     * @return \Illuminate\Http\Response
     */
    public function edit(Attr $attr)
    {
        $attrs=Attr::get();
        return view('attr.edit',compact('attr','attrs'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Attr  $attr
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Attr $attr)
    {
        $attr->update($request->all());
        return redirect()->route('attr.attr.index')->with('success','属性更新成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Attr  $attr
     * @return \Illuminate\Http\Response
     */
    public function destroy(Attr $attr)
    {
        // 判断是否当前属性是否有子属性
        if($attr->hasChild($attr)){
            return back()->with('error','请先删除子属性');
        }
        // 将分类属性表中属性id等于当前id的属性数据删除
        CategoryAttr::where('attr_id', $attr['id'])->delete();
        // 删除选中属性
        $attr->delete();
        // 跳转回首页
        return back()->with('success','删除成功');

    }
}
